package me.illtamer.infinite.file.parser;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.config.Configuration;
import me.illtamer.infinite.file.FileType;
import me.illtamer.infinite.file.source.FileSource;
import me.illtamer.infinite.hook.TranslatorAdaptor;
import me.illtamer.infinite.pojo.Response;
import me.illtamer.infinite.pojo.TransObject;
import me.illtamer.infinite.util.JsonUtil;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
public class YamlParser implements TypeParser {

    @Override
    public void parse(TranslatorAdaptor adaptor, FileSource source) throws InvalidConfigurationException, IOException {
        YamlConfiguration yaml = YamlConfiguration.loadConfiguration(new File(source.getName()));
        yaml.loadFromString(source.getContent());

        List<Map<String, String>> responseList = new ArrayList<>();

        long size = 0;
        LinkedHashMap<String, String> requestMap = new LinkedHashMap<>();
        List<LinkedHashMap<String, String>> translateMapList = new LinkedList<>();

        List<String> list = new LinkedList<>(yaml.getKeys(true));
        for (int i = 0; i < list.size(); ++ i) {
            String key = list.get(i);
            // 检查是否存在下一级
            if (i != list.size()-1 && list.get(i+1).startsWith(key + ".")) continue;
            Object object = yaml.get(key);
            if (!(object instanceof String)) continue;
            String value = ((String) object)
                    .replace("<", "=#").replace(">", "#=");

            if (size + value.length() > adaptor.getMaxLength()) {
                if (value.length() > adaptor.getMaxLength())
                    throw new IllegalArgumentException("Too long text length ! Limited: " + adaptor.getMaxLength() + " Found: " + value.length());
                translateMapList.add(requestMap);
                requestMap = new LinkedHashMap<>();
                requestMap.put(key, value);
                size = value.length();
            } else {
                requestMap.put(key, value);
                size += value.length();
            }
        }
        translateMapList.add(requestMap);
        for (LinkedHashMap<String, String> perRequest : translateMapList) {
            StringBuilder builder = new StringBuilder();
            for (String value : perRequest.values())
                builder.append(value).append("\n");
            String response = adaptor.translate(builder.toString(), "auto", "zh")
                    .replace("#=", ">").replace("=#", "<");

            TransObject object = JsonUtil.getObject(response);
            if (object.getResponse() != Response.SUCCESS) {
                log.warn("Failed translate {}", object);
                continue;
            }

            AtomicInteger i = new AtomicInteger();
            List<String> values = object.getTransPairs().stream().map(TransObject.TransPair::getDst).collect(Collectors.toList());
            Map<String, String> resultMap = perRequest.entrySet().stream().collect(Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> values.get(i.getAndIncrement())
            ));

            responseList.add(resultMap);
        }

        File targetFile = new File(Configuration.TARGET_FOLDER, source.getName());
        if (!targetFile.createNewFile()) {
            log.warn("Can not create file({}), is it already exists ?", targetFile.getAbsolutePath());
        }

        responseList.forEach(map -> map.forEach(yaml::set)) ;
        yaml.save(targetFile);
    }

    @Override
    public FileType parserType() {
        return FileType.YAML;
    }

}
